package org.god.core;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class JdbcTransaction implements Transaction{
    private Connection connection;
    private boolean autoCommit;

    public JdbcTransaction(DataSource dataSource,boolean autoCommit) {
        this.autoCommit = autoCommit;
        this.dataSource = dataSource;
    }

    private DataSource dataSource;
    @Override
    public void commit() {
        try {
            connection.commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void rollback() {
        try {
            connection.rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void close() {
        try {
            connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //开启连接
    @Override
    public void openConnection(){
        if(connection == null){
            try {
                this.connection = dataSource.getConnection();
                this.connection.setAutoCommit(autoCommit);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

    }
    //获取连接
    @Override
    public Connection getConnection(){
        return connection;
    }
}
